<template>
  <div class="form-rules">
    <el-form ref="form" :model="form" label-width="80px">
      <el-descriptions title="员工档案新增" border :column="3" size="medium">
        <el-descriptions-item
          v-for="field in filteredData"
          :key="field.id"
          border
          :label="field.name"
        >
          <el-form-item>
            <el-input
              v-if="
                'string' === field.type &&
                  !excludeFields.includes(field.field) &&
                  !selectFields.includes(field.field) &&
                  field.field !== 'gender' &&
                  field.field !== 'job_status' &&
                  field.field !== 'education_nature' &&
                  field.field !== 'registered_residence' &&
                  field.field !== 'work_experience'
              "
              v-model="form[field.field]"
              clear="input-item"
              :maxlength="
                form[field.field]?.maxlength ? form[field.field]?.maxlength : ''
              "
            />
            <div v-else-if="'file' === field.type">
              <el-upload
                v-if="
                  'one_inch_photo' === field.field ||
                    'identity_card_front' === field.field ||
                    'identity_card_reverse' === field.field
                "
                class="avatar-uploader"
                :action="action"
                :on-exceed="exceed"
                :show-file-list="false"
                :on-success="
                  ($event) => handleAvatarSuccess($event, field.field)
                "
                :before-upload="beforeAvatarUpload"
                :data="uploadData(field?.field)"
              >
                <div v-if="form[field.field]" class="avatar">
                  <img :src="form[field.field]" class="avatar-img">
                </div>
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
              <el-upload
                v-else
                class="upload-demo"
                drag
                :on-exceed="exceed"
                :action="action"
                :on-success="($event) => handleAvatarSuccess($event, name)"
                :limit="1"
                :before-upload="beforeUpload"
              >
                <i class="el-icon-upload" />
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <div slot="tip" class="el-upload__tip">不能超过2MB的文件</div>
              </el-upload>
            </div>
            <el-date-picker
              v-else-if="'date' === field.type"
              v-model="form[field.field]"
              value-format="yyyy-MM-dd"
              format="yyyy 年 MM 月 dd 日"
              align="right"
              type="date"
              placeholder="点击选项日期"
            />

            <el-select
              v-else-if="excludeFields.includes(field.field)"
              v-model="form[field.field]"
              :filterable="true"
            >
              <el-option
                v-for="item in options[field.field]"
                :key="item.id"
                :label="getOptionLabel(item, field.field)"
                :value="item.id"
              />
            </el-select>
            <addressSelect
              v-else-if="field.field === 'domicile_id'"
              v-model="form[field.field]"
            />
            <el-cascader
              v-else-if="selectFields.includes(field.field)"
              v-model="form[field.field]"
              :options="getCascaderOptions(field.field)"
              :props="getCascaderProps(field.field)"
            />
            <el-select
              v-else-if="field.field === 'gender'"
              v-model="form[field.field]"
            >
              <el-option label="男" value="1" />
              <el-option label="女" value="0" />
            </el-select>
            <el-select
              v-else-if="field.field === 'job_status'"
              v-model="form[field.field]"
            >
              <el-option label="在职" value="1" />
              <el-option label="离职" value="0" />
            </el-select>
            <el-select
              v-else-if="field.field === 'education_nature'"
              v-model="form[field.field]"
            >
              <el-option label="成人教育" value="1" />
              <el-option label="自考" value="0" />
              <el-option label="统招" value="0" />
            </el-select>
            <el-select
              v-else-if="field.field === 'registered_residence'"
              v-model="form[field.field]"
            >
              <el-option label="农业户口" value="1" />
              <el-option label="非农业户口" value="0" />
            </el-select>
            <!-- <a class="education" v-else-if="field.field === 'work_experience'"
            @click="showCreateDialog" >添加{{ field.name }}</a
            > -->
          </el-form-item>
        </el-descriptions-item>
      </el-descriptions>
      <div class="submit-btn">
        <el-button type="primary" plain @click="submit">提交</el-button>
      </div>
    </el-form>

  </div>
</template>
<script>
import { getFieldsList } from '@/api/customFields.js'
import { batchImport } from '@/api/onboarding'
import addressSelect from '@/components/AddressSelector/index.vue'
import {
  getSchool,
  getBank,
  getNation,
  getMarriage,
  getPolitic,
  getPosition,
  getDept,
  getDeptpeople,
  getEducation,
  getDormitory
} from '@/api/basic'
import FormWithDialog from '@/components/WorkExperienceForm/withDialog'
import { FormStruct } from '@/components/WorkExperienceForm/index'
export default {
  components: {
    addressSelect,
    FormWithDialog
  },
  data() {
    return {
      date: '',
      formDialog: {
        draft: { ...FormStruct },
        visible: false,
        mode: null // EDIT || CREATE
      },
      fileList: [],
      fields: [],
      blacklist: ['86', '15', '16'], // 黑名单
      form: {},
      action: process.env.VUE_APP_UPLOAD + 'api/v1/upload/file',
      pickerOptions: {
        // 禁用时间
        disabledDate(time) {
          return false
        },
        shortcuts: [
          {
            text: '明天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '前天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 2)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      date_picker: false, // 显示日期选择
      options: {
        nation_id: [],
        marital_id: [],
        school_id: [],
        bank_id: [],
        politic_id: [],
        position_id: [],
        department_id: [],
        leader_id: [],
        education_id: [],
        domicile_id: [],
        room_id: []
      },
      excludeFields: [
        'nation_id',
        'education_id',
        'marital_id',
        'school_id',
        'bank_id',
        'politic_id',
        'position_id',

        'leader_id'
      ],
      selectFields: ['domicile_id', 'department_id', 'room_id']
    }
  },
  computed: {
    filteredData() {
      return this.fields.filter(
        (item) => !this.blacklist.includes(item.id.toString())
      )
    },
    getOptionLabel() {
      return (item, fieldName) => {
        if (fieldName === 'nation_id') {
          return item.nation
        } else if (fieldName === 'school_id') {
          return item.school_name
        } else if (fieldName === 'bank_id') {
          return item.bankName
        } else if (fieldName === 'leader_id') {
          return item.username
        } else {
          return item.name
        }
      }
    }
  },
  created() {
    this.getDataAll()
    this.getFields()
  },
  mounted() {},
  methods: {
    getDataAll() {
      getNation().then((res) => {
        this.options.nation_id = res.data
      })
      getMarriage().then((res) => {
        this.options.marital_id = res.data
      })
      getSchool().then((res) => {
        this.options.school_id = res.data
      })
      getBank().then((res) => {
        this.options.bank_id = res.data
      })
      getPolitic().then((res) => {
        this.options.politic_id = res.data
      })
      getPosition().then((res) => {
        this.options.position_id = res.data
      })
      getDept().then((res) => {
        this.options.department_id = res.data
      })
      getDeptpeople().then((res) => {
        this.options.leader_id = res.data
      })
      getEducation().then((res) => {
        this.options.education_id = res.data
      })
      getDormitory().then((res) => {
        const newData = res.data.map((item) => {
          return {
            ...item,
            name: item.address // 将 address 替换为 name
          }
        })
        this.options.room_id = newData
      })
      console.log(this.options, 321312312312)
      console.log(this.domicile_idOptions, 321312312312)
    },
    getCascaderOptions(field) {
      return this.options[field]
    },
    getCascaderProps(field) {
      if (field === 'room_id') {
        return {
          label: 'name',
          value: 'id',
          children: 'room'
        }
      } else {
        return {
          label: 'name',
          value: 'id',
          children: 'children'
        }
      }
    },
    // 限制文件上传
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 <= 2
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    uploadData(name) {
      const data = {}
      if (name === 'identity_card_front') {
        data.type = 'idcard'
        data.analysis = 1
        data.idcardType = 'front'
      }
      if (name === 'identity_card_reverse') {
        data.type = 'idcard'
        data.analysis = 1
        data.idcardType = 'back'
      }
      return data
    },
    async getFields() {
      try {
        const data = ['user_details', 'user_companys']
        const res = await getFieldsList({ table: JSON.stringify(data) })
        if (res.status === 'success') {
          const data = this.fields.filter(
            (item) => !this.blacklist.includes(item.id.toString())
          )
          this.form = data.reduce((prev, current) => {
            prev[current] = ''
            return prev
          }, {})

          this.fields = res.data
          console.log(this.form, 1111111111)
        }
      } catch (error) {
        if (error.response?.data.code === 400) {
          this.$message({
            type: 'error',
            message: error.response.data.message
          })
        } else if (error.response?.status === 422) {
          this.$message({
            type: 'error',
            message: error.response.data.message
          })
        }
      }
    },
    // 提交按钮
    submit() {
      console.log(this.form, 231321312)
      this.postData()
    },
    async postData() {
      try {
        let data = []
        data = Object.keys(this.form).map((key) => {
          return { [key]: this.dataObject[key] }
        })
        console.log(data)
        console.log(this.form, 321321321)
        const res = await batchImport(data)
        if (res.status === 'success') {
          this.$message({
            type: 'success',
            message: '导入成功'
          })
        }
      } catch (error) {
        if (error.response?.data.code === 400) {
          this.$message({
            type: 'error',
            message: error.response.data.message
          })
        } else if (error.response?.status === 422) {
          this.$message({
            type: 'error',
            message: error.response.data.message
          })
        }
      }
    },
    exceed() {
      this.$message.error('超出可上传最大量')
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 <= 2
      if (!isJPG && !isPNG) {
        this.$message.error('图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }
      return isJPG || (isPNG && isLt2M)
    },
    // 图片上传成功
    handleAvatarSuccess(res, name) {
      const { data } = res
      if (data?.analysis?.error_code) {
        const m = {
          identity_card_front: '身份证正面(人像面)识别失败 请重新上传',
          identity_card_reverse: '身份证反面(国徽面)识别失败 请重新上传'
        }

        const errMsg = m[name] ?? '上传的信息识别有误请重新上传'
        this.$notify.error({
          title: '错误',
          message: errMsg
        })
        return
      }
      switch (name) {
        case 'identity_card_front':
          this.form.identity_card = data.analysis.result.number
          this.form.name = data.analysis.result.name
          this.form.birthday_at = data.analysis.result.birth
          const age = this.getAge(data.analysis.result.birth)
          this.form.age = age / 1
          this.form.gender = data.analysis.result.sex
          break

        case 'identity_card_reverse':
          this.form.identity_card_at = data.analysis.result.valid_to
          break
      }
      this.form[name] = data.path
      console.log(this.form[name], name, 111111111)
      console.log(this.form)
      this.$forceUpdate()
    }
  }
}
</script>
<style lang="scss" scoped>
:deep(.el-descriptions-item__label) {
  text-align: center !important;
}
.education{
  color: rgb(24, 144, 255);
}
.submit-btn {
  display: flex;
  flex-direction: row-reverse;
  padding: 20px 0;
}

.el-descriptions-item__cell {
  padding: 10px 10px 25px 10px !important;
}

:deep(.el-form-item) {
  margin: 10px 0 !important;
}

:deep(.el-form-item__content) {
  margin-left: 0 !important;
}

.form-rules {
  width: 100%;
  // display: flex;
  flex-direction: row;
  justify-content: center;
  padding: 50px;
  background-color: #fff;
  overflow-x: auto;
}

.input-item {
  width: 50%;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 200px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-img {
  max-width: 100%;
  max-height: 100%;
}
.el-upload-list--text {
  width: 395px !important;
}
</style>
